import {
  Component,
  ViewChild,
  Injector,
  Output,
  EventEmitter,
  ElementRef,
} from "@angular/core";
import { ModalDirective } from "ngx-bootstrap";
import { AppComponentBase } from "@shared/common/app-component-base";

import * as moment from "moment";
import { finalize } from "rxjs/operators";
import {
  MainTaskServiceProxy,
  TaskDto,
  MainTaskGoProductionDto,
  NameValueDtoOfNameValueDto,
  PipelineServiceProxy,
  SideTaskServiceProxy,
  NameValueDto,
  TeamGroupTaskServiceProxy,
  PipelineUsersInput,
} from "@shared/service-proxies/service-proxies";
import { LazyLoadEvent } from "primeng/api";

@Component({
  selector: "boundUserModal",
  templateUrl: "./bound-user-modal.component.html",
})
export class BoundUserModalComponent extends AppComponentBase {
  @ViewChild("actionModal") modal: ModalDirective;
  @ViewChild("dueDatePicker") dueDatePicker: ElementRef;
  @ViewChild("tmplCombobox") tmplCombobox: ElementRef;

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  dueDate = new Date();
  event?: LazyLoadEvent;
  id: string;
  pipelineId: string;
  mainTeamGroup: string;
  remark: string;
  teamGroupName = new Array<NameValueDto>();
  teamGroups = new Array<NameValueDto>();
  type: number;

  constructor(
    injector: Injector,
    private _teamGroupTaskService: TeamGroupTaskServiceProxy
  ) {
    super(injector);
  }

  show(
    id: string,
    mainTeamGroup: string,
    type: number,
    pipelineId: string,
    event?: LazyLoadEvent
  ): void {
    this.id = id;
    this.pipelineId = pipelineId;
    this.event = event;
    this.type = type;
    this.active = true;
    this._teamGroupTaskService
      .findUsers(mainTeamGroup, type)
      .subscribe((result) => {
        this.teamGroups = result;
        this.modal.show();
      });
  }

  save(): void {
    this.saving = true;
    var input = new PipelineUsersInput();
    input.id = this.id;
    input.remark = this.remark;
    input.dueTime = moment(this.dueDate).add(8, "hours");
    input.pipelineId = this.pipelineId;
    var user = Array<number>();
    this.teamGroupName.forEach((item) => {
      user.push(Number.parseInt(item.value));
    });
    input.userIds = user;
    if (this.type == 1) {
      this._teamGroupTaskService
        .boundPipelineUser(input)
        .pipe(
          finalize(() => {
            this.saving = false;
          })
        )
        .subscribe((result) => {
          this.notify.info("绑定成功");
          this.close();
          this.modalSave.emit(this.event);
        });
    } else if (this.type == 2) {
      this._teamGroupTaskService
        .boundNodeUser(input)
        .pipe(
          finalize(() => {
            this.saving = false;
          })
        )
        .subscribe((result) => {
          this.notify.info("绑定成功");
          this.close();
          this.modalSave.emit(this.event);
        });
    }
  }

  close(): void {
    this.saving = false;
    this.modal.hide();
  }
}
